package com.linsen.core.rabbitmq.service;

import com.linsen.core.rabbitmq.constant.DelayedConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyong
 * @date 2023/3/13
 */
@RequiredArgsConstructor
public class RabbitMQService {
    private final RabbitTemplate rabbitTemplate;

    /**
     * 发送队列消息
     *
     * @param routingKey 消息队列路由
     * @param data       消息体
     */
    public void sendMessage(String routingKey, Object data) {
        rabbitTemplate.convertAndSend(routingKey, data);
    }

    /**
     * 发送队列消息
     *
     * @param exchange   消息队列交换机
     * @param routingKey 消息队列路由
     * @param data       消息体
     */
    public void sendMessage(String exchange, String routingKey, Object data) {
        rabbitTemplate.convertAndSend(exchange, routingKey, data);
    }

    /**
     * 发送死信队列消息
     *
     * @param routingKey 消息队列路由
     * @param data       消息体
     * @param timeUnit   时间单位
     * @param timeout    超时时间
     */
    public void sendDelayedMessage(String routingKey, Object data, TimeUnit timeUnit, long timeout) {
        rabbitTemplate.convertAndSend(
                DelayedConstant.DELAYED_EXCHANGE,
                routingKey,
                data,
                message -> RabbitMQOptions.delay(message, timeUnit, timeout)
        );
    }
}
